/**
 * 判断数值型字符串是否是数值型
 * @param {*} val 
 * @param {*} type 
 */
let _ifNum = (val, type) => {
    // 返回true:满足   false:不满足
    // type:int/float
    if (!parseFloat(val)) {
        return false;
    }
    var str = String(val);
    var point = 0;
    var off = true;
    for (var i = 0; i < str.length; i++) {
        if (isNaN(Number(str[i]))) {
            //不是数字
            if (str[i] == '.') {
                point++;
            } else {
                off = false;
                break;
            }
        }
    }
    if (type == 'int') {
        (off && !point) ? '' : off = false;
    }
    if (type == 'float') {
        (off && point <= 1 && str[str.length - 1] != '.' && str[0] != '.') ? '' : off = false;
    }
    return off;
};

let toRad = (d) => { return d * Math.PI / 180; }

/**
 * 计算两个经纬度之间的距离
 * @param {*} lat1 纬度
 * @param {*} lng1 经度
 * @param {*} lat2 
 * @param {*} lng2 
 */
let _getDisance = (lat1, lng1, lat2, lng2) => {
    lat1 = Number(lat1);
    lng1 = Number(lng1);
    lat2 = Number(lat2);
    lng2 = Number(lng2);
    var dis = 0;
    var radLat1 = toRad(lat1);
    var radLat2 = toRad(lat2);
    var deltaLat = radLat1 - radLat2;
    var deltaLng = toRad(lng1) - toRad(lng2);
    var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
    return dis * 6378137;
}

/**
 * ISO时间和时间戳的相差秒数 timeNum一定要大于isoTime
 * @param {} isoTime 
 * @param {*} timeNum 
 */
let _timeDiff = (isoTime, timeNum) => {
    let dateee = new Date(isoTime).toJSON();
    let date = new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
    let nowTime = timeNum;
    let oldTime = Date.parse(date)
    if (String(nowTime).length > 10) {
        nowTime = parseInt(nowTime / 1000);
    }
    if (String(oldTime).length > 10) {
        oldTime = parseInt(oldTime / 1000);
    }
    return nowTime - oldTime;
}

/**
 * 学生位置删除多余的字段并返回
 * @param {*} doc 
 */
let _delOthLocation = (doc) => {
    try {
        delete doc['Wifi'];
        delete doc['ICCID'];
        delete doc['Send-Length'];
        delete doc['POST'];
        delete doc['Send-Type'];
        delete doc['Connection'];
        delete doc['Server-id'];
        delete doc['Serial-Number'];
        delete doc['Host'];
        delete doc['Content-Length'];
        delete doc['Report-Count'];
        delete doc['Gsensor-Count'];
        delete doc['Start-Count'];
        delete doc['Wifi-Search-Count'];
        delete doc['Parameter-Label'];
        delete doc['App-Version'];
    } catch (e) { }
    return doc;
}

module.exports = {
    _ifNum,
    _getDisance,
    _timeDiff,
    _delOthLocation
}






